package com.ruoyi.web.service.Impl;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.pinyin.PinYinUtils;
import com.ruoyi.web.domain.*;
import com.ruoyi.web.domain.vo.TakeversionDetaillist;
import com.ruoyi.web.mapper.MesConfigMapper;
import com.ruoyi.web.mapper.MesMakeVersionMapper;
import com.ruoyi.web.mapper.MesPlatemakingMapper;
import com.ruoyi.web.service.ProducePrintService;
import com.ruoyi.web.service.ProduceService;
import com.ruoyi.web.vo.MesMachine;
import com.ruoyi.web.vo.Produce;
import com.ruoyi.web.vo.ProducePrint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.web.mapper.MesTakeVersionMapper;
import com.ruoyi.web.service.IMesTakeVersionService;

import javax.annotation.Resource;

/**
 * 取版Service业务层处理
 *
 * @author wxt
 * @date 2024-02-20
 */
@Service
public class MesTakeVersionServiceImpl implements IMesTakeVersionService {
    @Resource
    private MesTakeVersionMapper mesTakeVersionMapper;

    @Resource
    private MesConfigMapper configMapper;

    @Resource
    private MesMakeVersionMapper mesMakeVersionMapper;

    @Resource
    private MesPlatemakingMapper mesPlatemakingMapper;

    @Resource
    private ProduceService produceService;
    @Resource
    private ProducePrintService producePrintService;

    /**
     * 查询取版
     *
     * @param id 取版主键
     * @return 取版
     */
    @Override
    public MesTakeVersion selectMesTakeVersionById(Long id) {
        MesTakeVersion data = mesTakeVersionMapper.selectMesTakeVersionById(id);
        return data;
    }

    /**
     * 查询取版列表
     *
     * @param mesTakeVersion 取版
     * @return 取版
     */

    @DataScope(deptAlias = "t",userAlias = "u1")
    @Override
    public List<MesTakeVersion> selectMesTakeVersionList(MesTakeVersion mesTakeVersion) {
        return mesTakeVersionMapper.selectMesTakeVersionList(mesTakeVersion);
    }


    @Override
    public List<TakeversionDetaillist> VersionDetaillist() {
        return mesTakeVersionMapper.VersionDetaillist();
    }

    /**
     * 新增取版
     *
     * @param mesTakeVersion 取版
     * @return 结果
     */
    @Transactional
    @Override
    public AjaxResult insertMesTakeVersion(MesTakeVersion mesTakeVersion) {
        mesTakeVersion.setCreateTime(DateUtils.getNowDate());
        mesTakeVersion.setCreateBy(SecurityUtils.getUsername());
        Map<String, Object> map = new HashMap<>();
        map.put("columnName", "take_code");
        map.put("tableName", "mes_take_version");
        int maxNum = configMapper.getMaxId(map);
        String code = PinYinUtils.getCodeNormal(maxNum, "QB");
        mesTakeVersion.setTakeCode(code);

        //取板验证
//        if (mesTakeVersion.getMesTakeversionDetailList() != null &&
//            !mesTakeVersion.getMesTakeversionDetailList().isEmpty()){
//            validate(mesTakeVersion.getMachineId(),mesTakeVersion.getMesTakeversionDetailList());
//        }

        mesTakeVersion.setStatus("2");
        int rows = mesTakeVersionMapper.insertMesTakeVersion(mesTakeVersion);
        insertMesTakeversionDetail(mesTakeVersion);


        //提交操作
        MesTakeVersion Info = mesTakeVersionMapper.selectMesTakeVersionById(mesTakeVersion.getId());//查询数据库
        List<MesTakeversionDetail> mesDetailList = Info.getMesTakeversionDetailList();
        if (!mesDetailList.isEmpty()) {
            //贴数集合
            List<String> pieceId = mesDetailList.stream().map(it -> it.getPieceId())
                    .collect(Collectors.toList());
            String[] pieceIds = pieceId.toArray(new String[0]);//贴数id
            List<String> ProduceId = mesDetailList.stream().map(MesTakeversionDetail::getProduceId)
                    .distinct().collect(Collectors.toList());
            MesMakeversionDetail makede = new MesMakeversionDetail();
            makede.setPieceIds(pieceIds);//贴数集合
            //批量修改贴状态为取板
            mesMakeVersionMapper.updistakes(makede);
            for (String produceid : ProduceId) {
                Produce produce= produceService.getById(produceid);
                int status=Integer.parseInt(produce.getStatus());
                if(status>5 && status<19){
                }else{
                    makede.setProduceId(produceid);//生产单id
                    makede.setMakeStatus("5");//生产单状态(已取版)
                    mesMakeVersionMapper.updateproducestatus(makede);
                }
            }
            for (MesTakeversionDetail mesTakeversionDetail : mesDetailList) {//回写取板人和时间
                MesPlatemakingDetail Detail = new MesPlatemakingDetail();
                Detail.setTakeUser(Info.getTakeUser());
                Detail.setTakeDate(Info.getTakeDate());
                Detail.setProducePrintId(mesTakeversionDetail.getProducePrintId());
                mesPlatemakingMapper.updatetake(Detail);
            }
        }

        return AjaxResult.success("新增成功");
    }

    //取板验证
    private int validate(String machineId, List<MesTakeversionDetail> data) {
//        List<MesTakeVersion> t=new ArrayList<>();//按纸张编码存库存量及印刷量等
//        for (MesTakeversionDetail take: data) {//循环生产印刷单
//            MesTakeVersion m = new MesTakeVersion();
//            m.setMachineId(machineId);
//            m.setPrintId(take.getProducePrintId());
//            MesTakeVersion takeVersion = mesTakeVersionMapper.selectValidate(m);
////            double AlreadyNum = takeVersion.getAlreadyNum();//已选择生产单用纸量
////            double StayNum = takeVersion.getStayNum();//待印刷数量
////            double MachineNum = takeVersion.getMachineNum();//机台库存量
//            boolean isadd=true;
//            for (MesTakeVersion s:t){
//                if (Objects.equals(s.getPaperNo(), takeVersion.getPaperNo())){//如果纸张编码相同
//                    s.setAlreadyNum(s.getAlreadyNum()+(takeVersion.getAlreadyNum()/1000));
//                    s.setStayNum(s.getStayNum()+(takeVersion.getStayNum()/1000));
//                    isadd=false;
//                }
//            }
//            if (isadd){
//                m.setAlreadyNum(takeVersion.getAlreadyNum()/1000);//已选择生产单用纸量
//                m.setStayNum(takeVersion.getStayNum()/1000);//待印刷数量
//                m.setMachineNum(takeVersion.getMachineNum());//机台库存量
//                m.setPaperNo(takeVersion.getPaperNo());//纸张编码
//                t.add(m);
//            }
//        }

//        for (MesTakeVersion version:t){
//            int result = Double.compare(version.getAlreadyNum(), version.getMachineNum()-version.getStayNum());
//            if (result>0){
//                throw new ServiceException("纸张编码为"+version.getPaperNo()+"的用纸量大于机台库存量减去待印刷量");
//            }
//        }

        String printIds = data.stream()
                .map(MesTakeversionDetail::getProducePrintId) // 提取印刷单
                .collect(Collectors.joining(","));

        MesTakeVersion m = new MesTakeVersion();
        m.setMachineId(machineId);
        m.setPrintId(printIds);
        List<MesTakeVersion> takeVersions = mesTakeVersionMapper.selectValidates(m);
        for (MesTakeVersion version : takeVersions) {
            Double AlreadyNum = version.getAlreadyNum() == null ? 0 : version.getAlreadyNum() / 1000;//已选择生产单用纸量
            Double StayNum = version.getStayNum() == null ? 0 : version.getStayNum() / 1000;//待印刷数量
            Double MachineNum = version.getMachineNum() == null ? 0 : version.getMachineNum();//机台库存量
            int result = Double.compare(AlreadyNum, MachineNum - StayNum);
            if (result > 0) {
                throw new ServiceException("纸张编码为" + version.getPaperNo() + "的用纸量大于机台库存量减去待印刷量");
            }
        }
        return 0;
    }

    ;

    /**
     * 修改取版
     *
     * @param mesTakeVersion 取版
     * @return 结果
     */
    @Transactional
    @Override
    public int updateMesTakeVersion(MesTakeVersion mesTakeVersion) {
        if (Objects.equals(mesTakeVersion.getStatus(), "2")) {//提交

//            MesTakeVersion Info= mesTakeVersionMapper.selectMesTakeVersionById(mesTakeVersion.getId());//查询数据库
//            List<MesTakeversionDetail> mesDetailList = Info.getMesTakeversionDetailList();
//            if (!mesDetailList.isEmpty()) {
//                //贴数集合
//                List<String> pieceId = mesDetailList.stream().map(it -> it.getPieceId())
//                        .collect(Collectors.toList());
//                String[] pieceIds = pieceId.toArray(new String[0]);//贴数id
//
//                List<String> ProduceId=  mesDetailList.stream().map(MesTakeversionDetail::getProduceId)
//                .distinct().collect(Collectors.toList());
//
//                MesMakeversionDetail makede=new MesMakeversionDetail();
//                makede.setPieceIds(pieceIds);//贴数集合
//
//                //批量修改贴状态为取板
//                mesMakeVersionMapper.updistakes(makede);
//
//                for (String produceid:ProduceId){
//                    makede.setProduceId(produceid);//生产单id
//                        makede.setMakeStatus("5");//生产单状态(已取版)
//                        mesMakeVersionMapper.updateproducestatus(makede);
//                }
//
//                for (MesTakeversionDetail mesTakeversionDetail: mesDetailList){//回写取板人和时间
//                    MesPlatemakingDetail Detail=new MesPlatemakingDetail();
//                    Detail.setTakeUser(Info.getTakeUser());
//                    Detail.setTakeDate(Info.getTakeDate());
//                    Detail.setProducePrintId(mesTakeversionDetail.getProducePrintId());
//                    mesPlatemakingMapper.updatetake(Detail);
//                }
//            }
        } else {
            mesTakeVersionMapper.deleteMesTakeversionDetailByTakeId(mesTakeVersion.getId());
            insertMesTakeversionDetail(mesTakeVersion);
        }
        return mesTakeVersionMapper.updateMesTakeVersion(mesTakeVersion);
    }

    /**
     * 批量删除取版
     *
     * @param ids 需要删除的取版主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteMesTakeVersionByIds(Long[] ids) {
        mesTakeVersionMapper.deleteMesTakeversionDetailByTakeIds(ids);
        return mesTakeVersionMapper.deleteMesTakeVersionByIds(ids);
    }

    /**
     * 删除取版信息
     *
     * @param id 取版主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteMesTakeVersionById(Long id) {
        mesTakeVersionMapper.deleteMesTakeversionDetailByTakeId(id);
        return mesTakeVersionMapper.deleteMesTakeVersionById(id);
    }

    /**
     * 新增取版明细信息
     *
     * @param mesTakeVersion 取版对象
     */
    public void insertMesTakeversionDetail(MesTakeVersion mesTakeVersion) {
        List<MesTakeversionDetail> mesTakeversionDetailList = mesTakeVersion.getMesTakeversionDetailList();
        Long id = mesTakeVersion.getId();
        if (StringUtils.isNotNull(mesTakeversionDetailList)) {
            List<MesTakeversionDetail> list = new ArrayList<MesTakeversionDetail>();
            for (MesTakeversionDetail mesTakeversionDetail : mesTakeversionDetailList) {
                mesTakeversionDetail.setTakeId(id);
                list.add(mesTakeversionDetail);
            }
            if (list.size() > 0) {
                mesTakeVersionMapper.batchMesTakeversionDetail(list);
            }
        }
    }
}
